package rs.webnet.android.kamere;

import rs.webnet.android.kamere.data.DataFetcher;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class SplashActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_layout);

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() == null) {
			noConnection();
			return;
		}
		if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
			Log.d("d", "online je");
			new Timer().execute();
		} else {
			noConnection();
			return;
		}
		// new Timer().execute();
	}

	private class Timer extends AsyncTask<Void, Void, Boolean> {
		boolean status = false;

		@Override
		protected Boolean doInBackground(Void... params) {
			status = DataFetcher.initReport(getApplicationContext());
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			while (status == false) {
			}
			Intent intent = new Intent(SplashActivity.this, KamereActivity.class);
			startActivity(intent);
			SplashActivity.this.finish();
		}

	}

	public void noConnection() {
		DataFetcher.initCameras(getApplicationContext());
		AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
		builder.setMessage("Nije moguce preuzimanje podataka!\nProverite internet konekciju!\nPodaci o stanju na putevima nisu dostupni.").setCancelable(false).setNegativeButton("U redu", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				Intent intent = new Intent(SplashActivity.this, KamereActivity.class);
				startActivity(intent);
				SplashActivity.this.finish();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
}
